package com.ruike.alisurface.services;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;

import com.ruike.alisurface.utils.ShareKey;
import com.ruike.alisurface.utils.ThreadUtils;
import com.ruike.alisurface.utils.TimeUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Author: voodoo
 * CreateDate: 2020/02/19 019 下午 03:08:04
 * Description: 网络监听的服务
 */
public class NetWorkListenerService extends Service {

    public TelephonyManager mTelephonyManager;
    public PhoneStatListener mListener;
    private NetWorkBroadCastReciver mNetWorkBroadCastReciver;
    public static int mGsmSignalStrength = -113;
    public static int mSendStrength = 0;//要上传的信号值   信号值负数      100加

    public static int getmSignalStrength() {
        if (mSendStrength < 0) {
            mSendStrength = 100 + mSendStrength;
        }
        L.i("当前信号强度改变 上传的signalStrength 值：" + mGsmSignalStrength + "==" + mSendStrength);
        return mSendStrength;
    }

    public int checkNumber = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        L.i("网络监听的服务 开启信号检测");
        // 开始监听
        mListener = new PhoneStatListener();
        // 获取telephonyManager
        mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        // 由于信号值变化不大时，监听反应不灵敏，所以通过广播的方式同时监听wifi和信号改变更灵敏
        mNetWorkBroadCastReciver = new NetWorkBroadCastReciver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);

        registerReceiver(mNetWorkBroadCastReciver, intentFilter);
        // 服务被创建的时候开始监听
        mTelephonyManager.listen(mListener, PhoneStatListener.LISTEN_SIGNAL_STRENGTHS);
        // 主动去查询当前网络信号
        Timer getNetWorkInfoTimer = new Timer();
        TimerTask getNetWorkInfoTimerTask = new TimerTask() {
            @Override
            public void run() {
                checkNumber++;
                if (checkNumber >= 20) {
                    checkNumber = 0;
//                    L.i("mqtt 重置机器重启次数 时间比对"+TimeUtils.millis2String(System.currentTimeMillis(),"HH:mm"));
                    if (TimeUtils.millis2String(System.currentTimeMillis(), "HH:mm").equals("00:00")) {
                        L.i("设置默认  重新设置重启日期", "  重置机器重启次数");
                        ShareUtils.getInstance().putInt(ShareKey.IS_OFFLINE_RESTART_APPCOUNT, 10);
                        String todoDay = TimeUtils.millis2String(System.currentTimeMillis(), "yyyy-MM-dd");
                        ShareUtils.getInstance().putString(ShareKey.OFFLINE_RESTART_DAY, todoDay);
                        ShareUtils.getInstance().putBoolean(ShareKey.IS_NETWORK_STATUS, false);
                    }
                }
                ThreadUtils.postUI(new Runnable() {
                    @Override
                    public void run() {
                        getNetWorkInfo();
                    }
                });
            }
        };
        getNetWorkInfoTimer.schedule(getNetWorkInfoTimerTask, 0, 3_000);
    }

    /**
     * 网络信号的变化监听
     */
    private class PhoneStatListener extends PhoneStateListener {
        @SuppressLint("NewApi")
        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
            super.onSignalStrengthsChanged(signalStrength);
            // 获取网络信号强度
            // 获取0-4的5种信号级别，越大信号越好,但是api23开始才能用
            mGsmSignalStrength = signalStrength.getGsmSignalStrength();
            L.i("当前信号强度改变 signalStrength 值：" + signalStrength.toString(), "级别==" + signalStrength.getLevel());
            // 网络信号改变时，获取网络信息
            getNetWorkInfo();
        }
    }


    /**
     * 接收网络状态改变的广播
     */
    class NetWorkBroadCastReciver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            getNetWorkInfo();
//            GetNetworkType(context);
        }
    }

    public static PhoneWaftListener mPhoneWaftListener;

    public static void setPhoneWaftListener(PhoneWaftListener phoneWaftListener) {
        mPhoneWaftListener = phoneWaftListener;
    }

    public interface PhoneWaftListener {
        void onStrengthsChanged(String type, int signalStrength, int level);

    }

    /**
     * 获取网络的信息
     */
    private void getNetWorkInfo() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            switch (info.getType()) {
                case ConnectivityManager.TYPE_WIFI: // WIFI
                    checkWifiState();
                    break;
                case ConnectivityManager.TYPE_MOBILE: // 移动网络,可以通过TelephonyManager来获取具体细化的网络类型
                    getNetworkLevel("TYPE_MOBILE", mGsmSignalStrength);
                    break;
                case ConnectivityManager.TYPE_ETHERNET: // 网线网络,
                    getNetworkLevel("TYPE_ETHERNET", 60);
                    break;
            }
        } else {
            getNetworkLevel("TYPE_MOBILE", mGsmSignalStrength);
        }
    }

    /**
     * 检查wifi是否处开连接状态
     *
     * @return
     */
    public boolean isWifiConnect() {
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return mWifiInfo.isConnected();
    }

    /**
     * 检查wifi强弱并更改图标显示
     */
    public void checkWifiState() {
        if (isWifiConnect()) {
            @SuppressLint("WifiManagerLeak") WifiManager mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();
            int wifi = -100;
            if (mWifiInfo != null) {
                wifi = mWifiInfo.getRssi();//获取wifi信号强度
            }
            //   L.i("当前信号强度改变：" + wifi);
            //wifi信号强度
            int signalLevel = WifiManager.calculateSignalLevel(wifi, 5);
            L.i("当前信号强度改变：" + wifi, "获取当前连接速度=" + mWifiInfo.getLinkSpeed(), "级别=" + signalLevel);
            getNetworkLevel("TYPE_WIFI", wifi);
        } else {
            getNetworkLevel("TYPE_WIFI", -100);
        }
    }

    /**
     * 判断网络速度
     */
    private boolean isFastMobileNetwork() {
        // 这里只简单区分两种类型网络，认为4G网络为快速，但最终还需要参考信号值
        return mTelephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_LTE;
    }

    /**
     * 设置网络级别
     */
    public void getNetworkLevel(String type, int mSignalStrength) {
        int level = 0;//级别
        mSendStrength = mGsmSignalStrength = mSignalStrength;
        if ("TYPE_WIFI".equals(type)) {
            if (mSignalStrength >= -55) {
                level = 4;
            } else if (mSignalStrength >= -60) {
                level = 3;
            } else if (mSignalStrength >= -70) {
                level = 2;
            } else if (mSignalStrength >= -90) {
                level = 1;
            } else if (mSignalStrength <= -100) {
                level = 0;
            }
        } else if ("TYPE_MOBILE".equals(type)) { //  这个是以asu 值计算的  0-31 之间
            if (mSignalStrength <= 0) {
                level = 0;
            } else if (mSignalStrength < 5) {
                level = 1;
            } else if (mSignalStrength < 10) {
                level = 2;
            } else if (mSignalStrength < 20) {
                level = 3;
            } else if (mSignalStrength < 32) {
                level = 4;
            } else {
                level = 5;//信号强度异常未知
            }
            if (mGsmSignalStrength > 0 && mGsmSignalStrength != 99) {
                mSendStrength = -113 + 2 * mGsmSignalStrength;
            } else {
                mSendStrength = mGsmSignalStrength;
            }
        } else if ("TYPE_ETHERNET".equals(type)) {
            level = 4;
        }

//        L.e("类型==" + type + "信号级别==" + level + "==信号强度==" + mSignalStrength + "==上传的信号强度==" + mSendStrength);
        if (mPhoneWaftListener != null) {
            mPhoneWaftListener.onStrengthsChanged(type, type.equals("TYPE_MOBILE") ? mSendStrength : mSignalStrength, level);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 服务被销毁的时候，停止监听并解绑广播接收器
        mTelephonyManager.listen(mListener, PhoneStatListener.LISTEN_NONE);
        unregisterReceiver(mNetWorkBroadCastReciver);
    }


    //获取网络状态的工具类
    public String GetNetworkType(Context context) {
        String strNetworkType = "";
        ConnectivityManager manager = (ConnectivityManager) context.
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        /*  NetworkInfo networkInfo = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE).getActiveNetworkInfo();*/
        if (networkInfo != null && networkInfo.isConnected()) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                strNetworkType = "WIFI";
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                String _strSubTypeName = networkInfo.getSubtypeName();

                L.e("网络", "Network getSubtypeName : " + _strSubTypeName);

                // TD-SCDMA   networkType is 17
                int networkType = networkInfo.getSubtype();
                switch (networkType) {
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                    case TelephonyManager.NETWORK_TYPE_1xRTT:
                    case TelephonyManager.NETWORK_TYPE_IDEN: //api<8 : replace by 11
                        strNetworkType = "2G";
                        break;
                    case TelephonyManager.NETWORK_TYPE_UMTS:
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    case TelephonyManager.NETWORK_TYPE_HSDPA:
                    case TelephonyManager.NETWORK_TYPE_HSUPA:
                    case TelephonyManager.NETWORK_TYPE_HSPA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_B: //api<9 : replace by 14
                    case TelephonyManager.NETWORK_TYPE_EHRPD: //api<11 : replace by 12
                    case TelephonyManager.NETWORK_TYPE_HSPAP: //api<13 : replace by 15
                        strNetworkType = "3G";
                        break;
                    case TelephonyManager.NETWORK_TYPE_LTE: //api<11 : replace by 13
                        strNetworkType = "4G";
                        break;
                    default:
                        // http://baike.baidu.com/item/TD-SCDMA 中国移动 联通 电信 三种3G制式
                        if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA") || _strSubTypeName.equalsIgnoreCase("WCDMA") || _strSubTypeName.equalsIgnoreCase("CDMA2000")) {
                            strNetworkType = "3G";
                        } else {
                            strNetworkType = _strSubTypeName;
                        }

                        break;
                }

                L.e("网络", "Network getSubtype : " + Integer.valueOf(networkType).toString());
            }
        }

        L.e("网络", "Network Type : " + strNetworkType);

        return strNetworkType;
    }


}
